package com.flats.webview;


import com.flats.model.entity.Flat;
import com.flats.service.transactional.TransactionalFlatService;
import com.flats.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

@Controller
public class FindFlatController {

    @Autowired
    TransactionalFlatService flatService;
    
    @RequestMapping(value = "/show.flats")
    public String viewFlats(Model model) {
        String  country = (String) Utils.getSession(Constants.COUNTRY);
        String  city = (String) Utils.getSession(Constants.CITY);
        String  street = (String) Utils.getSession(Constants.STREET);
        List<Flat> filter=new LinkedList<Flat>();
        if (country != null) {
            for (Flat flat : flatService.getAll()) {
                if (country.equals(flat.getAddress().getCountry())){
                    filter.add(flat);
                }
            }
            if (city != null) {
                Iterator<Flat> it = filter.iterator();
                while(it.hasNext()){
                    if(!city.equals(it.next().getAddress().getCity())){
                        it.remove();
                    }
                }
            }
            if (street != null) {
                Iterator<Flat> it = filter.iterator();
                while(it.hasNext()){
                    if(!street.equals(it.next().getAddress().getStreet())){
                        it.remove();
                    }
                }
            }
        }
        model.addAttribute("flats", filter);
        return "showFlats";
    }
}
